package org.jerrymouse.jsa4j.search.kv;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.analysis.tokenattributes.TermAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.util.Version;
import org.jerrymouse.jsa4j.db.kv.Indexer;
import org.jerrymouse.jsa4j.db.kv.Repository;
import org.jerrymouse.jsa4j.search.Searcher;

public class KVSearcher implements Searcher {
	Indexer indexer;
	private static Analyzer analyzer = new SmartChineseAnalyzer(
			Version.LUCENE_30);

	public void setIndexer(Indexer indexer) {
		this.indexer = indexer;
	}

	@Override
	public void makeIndex(String index, String content) {
		try {
			TokenStream tokenStream = analyzer.tokenStream(null,
					new StringReader(content));
			TermAttribute termAtt = (TermAttribute) tokenStream
					.getAttribute(TermAttribute.class);
			while (tokenStream.incrementToken()) {
				String c = termAtt.term();
				indexer.makeIndex(index, c);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@Override
	public List<String> search(String keyword, Integer max) {
		Set<String> keys = indexer.getKey(keyword);
		if (max != null) {
			for (int i = keys.size() - 1; i > max; i++) {
				keys.remove(i);
			}
		}
		if (keys != null)
			return new ArrayList<String>(keys);
		return null;
	}

	@Override
	public List<String> search(List<String> keywords, Integer max) {
		Set<String> set = new HashSet<String>();
		for (String keyword : keywords) {
			List<String> s = search(keyword, null);
			if (s == null)
				s=new ArrayList<String>();
			if (set.size() == 0)
				set.addAll(s);
			else
				set.retainAll(s);
		}
		List<String> list = new ArrayList<String>(set);
		if (max != null) {
			for (int i = set.size() - 1; i > max; i++) {
				list.remove(i);
			}
		}
		return list;
	}
}
